<template>
  <el-dialog v-model="dialog" title="修改采购商" width="700px" :close-on-click-modal="false">
    <div style="max-height: 400px; overflow-y: auto; display: flex; justify-content: center;">
      <el-form ref="elForm" :model="form" :rules="rules" label-width="150px" style="width: 600px;">
        <el-form-item label="商家类型" prop="buyerType">
          <el-select class="w120" v-model="form.buyerType" @change="changeBuyerType">
            <el-option v-for="item of buyerTypes" :label="item.listValue" :value="item.listKey" :key="item.listKey">
            </el-option>
          </el-select>
          <el-select class="w90 mL10" v-model="form.scType" v-show="form.isSchool == 'TRUE'">
            <el-option label="请选择" value=""></el-option>
            <el-option label="公立" value="PUBLIC"></el-option>
            <el-option label="私立" value="PRIVATE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="buyerName">
          <el-input placeholder="请输入名称" v-model="form.buyerName"></el-input>
        </el-form-item>
        <el-form-item label="负责人/法人代表" prop="legalPerson">
          <el-input placeholder="请输入负责人/法人代表" v-model="form.legalPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input placeholder="请输入联系电话" v-model="form.tel"></el-input>
        </el-form-item>
        <el-form-item label="经营地址" prop="areaId">
          <el-select class="w120" v-model="form.provinceId" @change="changeProvince">
            <el-option v-for="item of provinces" :label="item.label" :value="item.value" :key="item.value">
            </el-option>
          </el-select>
          <el-select class="w120 mL10" v-model="form.cityId" @change="changeCity">
            <el-option v-for="item of cities" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
          <el-select class="w120 mL10" v-model="form.areaId" @change="changeCountry">
            <el-option v-for="item of countries" :label="item.label" :value="item.value" :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属街道办" prop="streetAreaId">
          <el-select v-model="form.streetAreaId">
            <el-option v-for="item of streets" :label="item.listValue" :value="item.listKey" :key="item.listKey">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input placeholder="请输入详细地址" v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="绑定配送商" prop="relDlrIdArr">
          <el-select v-model="form.relDlrIdArr" multiple filterable remote reserve-keyword placeholder="请选择绑定配送商"
            :remote-method="getDlrs" @change="changeDlr" style="width: 450px;">
            <el-option v-for="item in dlrs" :key="item.GUID" :label="item.DLRNAME" :value="item.GUID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属代理商" prop="agentGuid">
          <el-select v-model="form.agentGuid">
            <el-option v-for="item of agents" :label="item.listValue" :value="item.listKey" :key="item.listKey">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市场人员" prop="marketer">
          <el-select v-model="form.marketer">
            <el-option v-for="item of marketers" :label="item.listValue" :value="item.listKey" :key="item.listKey">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业证图片">
          <el-upload action="/v2/consumer/imgupload" :file-list="bsLicList"
            :on-success="res => uploadFileSuccess(res, 'oss_bsLicImg')"
            :on-preview="previewImg"
            :on-exceed="_ => $message.error('请删除文件后再上传')"
            :on-remove="_ => form.oss_bsLicImg = ''"
            accept=".jpg,.jpeg,.png" :limit="1" :multiple="false"
            :http-request="$upload" list-type="picture-card">
            <el-icon class="avatar-uploader-icon">
              <plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="食品经营许可证图片">
          <el-upload action="/v2/consumer/imgupload" :file-list="foodLicenseList"
            :on-success="res => uploadFileSuccess(res, 'foodLicense')"
            :on-preview="previewImg"
            :on-remove="_ => form.foodLicense = ''"
            :on-exceed="_ => $message.error('请删除文件后再上传')"
            accept=".jpg,.jpeg,.png" :limit="1" :multiple="false"
            :http-request="$upload" list-type="picture-card">
            <el-icon class="avatar-uploader-icon">
              <plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="溯源模板" prop="ttsStyle" required>
          <el-radio-group v-model="form.ttsStyle">
            <el-radio label="CLASSIC">经典绿色</el-radio>
            <el-radio label="GOV">政府风格</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" @click="confirmUpdate">保存</el-button>
      <el-button @click="dialog = false">关闭</el-button>
    </template>
  </el-dialog>
  <!-- 图片预览 -->
  <div>
    <el-image-viewer @close="showImageViewer = false" :url-list="imageList" v-show="showImageViewer"/>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    inject,
    nextTick,
    getCurrentInstance,
  } from 'vue'
  import {
    Plus
  } from '@element-plus/icons-vue'

  const $getProvinces = inject('$getProvinces');
  const $getCities = inject('$getCities');
  const $getCountries = inject('$getCountries');
  const $post = inject('$post');
  const $upload = inject('$upload');
  const $message = inject('$message');
  const $emit = defineEmits(['confirm']);
  const { 
    ctx
  } = getCurrentInstance();

  // 省市区
  const provinces = reactive($getProvinces());
  const cities = ref([]);
  const countries = ref([]);
  const streets = ref([]);
  // 修改省
  const changeProvince = val => {
    cities.value = $getCities(val);
    countries.value = [];
    form.value.cityId = '';
    form.value.areaId = '';
  }
  // 修改市
  const changeCity = val => {
    countries.value = $getCountries(val);
    form.value.areaId = '';
  }
  // 修改区
  const changeCountry = val => {
    $post('/consumer/street', {
      areaId: val
    }).then(res => {
      streets.value = res.data;
    })
  }

  // 商家类型
  const buyerTypes = ref([])
  const schoolType = {
    'KINDSC': true,
    'PRISC': true,
    'MIDSC': true,
    'HIGSC': true,
    'UNVSC': true
  };
  const changeBuyerType = val => {
    form.value.scType = '';
    form.value.isSchool = schoolType[val] ? 'TRUE' : 'FALSE'
  }
  $post('/v2/consumer/buyerType').then(res => buyerTypes.value = res.data);

  // 代理商
  const agents = ref([]);
  $post('/v2/consumer/agentList').then(res => agents.value = res.data);

  // 市场人员
  const marketers = ref([]);
  const getMarketers = () => {
    $post('/v2/consumer/marketerList', {
      agentId: form.value.agentGuid
    }).then(res => marketers.value = res.data);
  }

  // 获取配送商列表
  const dlrs = ref([])
  const getDlrs = (dlrName = '') => {
    $post('/consumer/dlrlist', {
      dlrName,
      areaId: form.value.areaId,
      byGuid: form.value.guid
    }).then(res => dlrs.value = res.data);
  }
  // 修改配送商
  const changeDlr = val => {
    if (val.length > form.value.relJson.length) {
      // 代表新增
      let dlr = dlrs.value.find(item => item.GUID == val[val.length - 1]);
      form.value.relJson.push(dlr);
    } else {
      form.value.relJson = form.value.relJson.filter(item => val.includes(item.GUID));
    }
  }
  
  const bsLicList = ref([]);
  const foodLicenseList = ref([]);
  // 上传文件
  const uploadFileSuccess = (res, prop) => {
    $message.success('文件上传成功');
    form.value[prop] = res.data;
  }
  // 预览文件
  const showImageViewer = ref(false);
  const imageList = ref([]);
  const previewImg = file => {
    imageList.value = [file.url];
    showImageViewer.value = true;
  };

  const dialog = ref(false);

  const form = ref({
    guid: '',
    // 商家类型
    buyerType: '',
    scType: '',
    // 是否是学校
    isSchool: '',
    // 名称
    buyerName: '',
    // 负责人/法人代表
    legalPerson: '',
    // 联系电话
    tel: '',
    // 区域ID
    provinceId: '',
    cityId: '',
    countryId: '',
    areaId: '',
    // 所属街道办
    streetAreaId: '',
    // 详细地址
    address: '',
    // 绑定配送商
    relDlrIdArr: [],
    // 所属代理商
    agentGuid: '',
    // 市场人员
    marketer: '',
    // 硕源模板
    ttsStyle: ''
  });

  const rules = {
    buyerType: [{
      required: true,
      message: '请选择商家类型',
      trigger: 'change'
    }],
    buyerName: [{
      required: true,
      message: '请输入名称',
      trigger: 'change'
    }],
    legalPerson: [{
      required: true,
      message: '请输入负责人/法人代表',
      trigger: 'change'
    }],
    tel: [{
      required: true,
      message: '请输入联系电话',
      trigger: 'change'
    }, {
      validator: (rule, value, callback) => {
        if (/1[3-9]\d{9}/.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的手机号'));
        }
      },
      trigger: 'change'
    }],
    areaId: [{
      required: true,
      message: '请选择经营地址',
      trigger: 'change'
    }],
    address: [{
      required: true,
      message: '请输入详细地址',
      trigger: 'change'
    }],
    agentGuid: [{
      required: true,
      message: '请选择所属代理商',
      trigger: 'change'
    }],
    marketer: [{
      required: true,
      message: '请选择市场人员',
      trigger: 'change'
    }]
  };

  // 展示模态框
  const show = guid => {
    dialog.value = true;
    $post('/consumer/buyerInformation', {
      guid
    }).then(res => {
      form.value = res.data;
      if (res.data.relDlrId) {
        form.value.relDlrIdOld = res.data.relDlrId;
        form.value.relDlrIdArr = res.data.relDlrId.split(',');
      }
      form.value.provinceId = res.data.areaId.replace(/\d{4}$/, '0000');
      form.value.cityId = res.data.areaId.replace(/\d{2}$/, '00');
      dlrs.value = res.data.relJson;
      // 图片list
      if (res.data.bsLicImgs) {
        bsLicList.value = [{
          url: res.data.bsLicImgs
        }];
      } else {
        bsLicList.value = [];
      }
      if (res.data.foodLicense) {
        foodLicenseList.value = [{
          url: res.data.foodLicense
        }];
      } else {
        foodLicenseList.value = [];
      }
      getMarketers();
      changeCountry(form.value.areaId);
      cities.value = $getCities(form.value.provinceId);
      countries.value = $getCountries(form.value.cityId);
      getDlrs();
      // 清除表单校验
      nextTick(ctx.$refs.elForm.clearValidate);
    });
  }

  // 保存数据
  const confirmUpdate = () => {
    ctx.$refs.elForm.validate(res => {
      if (!res) return;
      form.value.relJson = JSON.stringify(form.value.relJson);
      form.value.relDlrId = form.value.relDlrIdArr.join(',');
      $post('/consumer/updateBuyer', form.value).then(res => {
        $message.success('更新成功');
        $emit('confirm');
        dialog.value = false;
        bsLicList.value = [];
        foodLicenseList.value = [];
      })
    })
  }

  defineExpose({
    show
  })
</script>

<style scoped="scoped">
  
  :deep(div.el-image-viewer__wrapper) {
    z-index: 3000 !important;
  }
  
</style>
